//网络请求服务器配置：https://developers.weixin.qq.com/miniprogram/dev/framework/ability/network.html
//1.服务器域名配置:https://blog.csdn.net/CC1991_/article/details/98481770
//2.特别使用限制。
//3.目前测试阶段先用http请求，实际开发的时候，是需要https，配置域名的。

// import cookie from 'js-cookie';

// 常见Http错误状态码
const HTTP_ERROR_CODE = {
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Forbidden',
  404: 'Not Found',
  405: 'Method Not Allowed',
  406: 'Not Acceptable',
  408: 'Request Timeout',
  414: 'Request URI Too Long',
  500: 'Internal Server Error',
  501: 'Not Implemented',
  502: 'Bad Gateway',
  503: 'Service Unavailable',
  504: 'Gateway Timeout',
  505: 'HTTP Version Not Supported'
};


const CONSTANT = {
  URL: 'https://www.baidu.com'//接口地址
};

let flag = 0;

function wxPromise(config) {
  let Authorization = wx.getStorageSync('Authorization') ? JSON.parse(decodeURIComponent(wx.getStorageSync('Authorization'))) : "";
  let header = {
    "Content-Type": "application/json;charset=UTF-8",
  };
  if (!/front\/login/g.test(config.url)) {//除了登录接口，其他接口都加token
    config.data.token = Authorization.token;
    header.cookie = `cs_session=${Authorization.token};`
  }

  // 'cookie':`cs_session=${};cs_staff=${wx.getStorageSync('Authorization')}`//设置cookie
  return new Promise(function(resolve, reject) {
    const fullurl = CONSTANT.URL + config.url;
    wx.request({
      url: fullurl,
      method: config.method,
      data: config.data,
      header: header,
      success(res) {
        resolve(res);
      },
      fail(res) {
        wx.showToast({
          title: 'wx.request fail',
          icon: 'none',
          duration: 1000,
          mask: true
        });
      }
    });
  });
}

export default function $http(config) {
  let pms = wxPromise(config);
  return pms.then(o => {
    // 转化后台返回retcode是字符串的情况
    o.data.retcode = parseInt(o.data.retcode, 10);
    o.data.result_rows = o.data.result_rows === undefined ? [] : o.data.result_rows;
    if (o.data.retcode !== 0) {
      if (o.data.retcode === 10002 || o.data.retcode === 10003) { //10002 被顶号 10003 接口要求必须登录，而没有传authorization值,这个值后端定
        wx.removeStorageSync('Authorization');
        let content = "";
        if (o.data.retcode === 10002) {
          content = "您的账号在别处登陆，请重新登录";
        } else if (o.data.retcode === 10003) {
          content = "登录状态过期，请重新登录";
        }
        if (flag === 0) {
          flag = 1;
          wx.showModal({
            title: '提示',
            content: content,
            showCancel: false,
            success(res) {
              if (res.confirm) {
                flag = 0;
                wx.redirectTo({
                  url: '/pages/login/login'
                });
              }
            }
          });
        }
      }else {
        if (flag === 0) {
          flag = 1;
          wx.showToast({
            title: `错误信息：${o.data.retmsg}`,
            icon: 'none',
            duration: 1500
          });
        }
      }
      // 控制台输出信息，方便提交后台排错
      console.info(`错误编码：${o.data.retcode}\n错误信息：${o.data.retmsg}\n接口地址：${config.url}\n输入参数：${JSON.stringify(config.data)}`);
    }
    return o.data;
  });
};

$http.get = function(url, data = {}, config = {}) {
  let cfg = {
    ...config,
    url,
    data,
    method: 'GET'
  };
  return this(cfg);
};

$http.post = function(url, data = {}, config = {}) {
  let cfg = { ...config,
    url,
    data,
    method: 'POST'
  };
  return this(cfg);
};
